<?php

namespace app\common\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;


class Video extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'video';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [];
    protected $resultSetType = 'collection';



    public function createVideo($data, $userInfo)
    {
        // 启动事务
        Db::startTrans();
        try {
            //添加视频
            $res = $this->allowField(true)->save($data);

            if (!$res) return ['code' => 0, 'msg' => '发布视频失败'];

            if ($data['money']) {
                //计算用户一共需要多少金额
                $totalMoney = $data['money'] * (int)$data['number'];
                //判断用户金额是否足够
                if ($totalMoney > $userInfo['money']) return ['code' => 0, 'msg' => '余额不足,请充值'];
                //扣减用户金额
                $userMoneyRes = (new MoneyLog)->saveUserMoney(2, 1, $userInfo['id'], $totalMoney, '发布视频红包');

                if (!$userMoneyRes) return ['code' => 0, 'msg' => '用户余额记录失败'];
                //添加红包
                $redEnvelopes = [
                    'video_id'      => $this->id,
                    'price'         => $data['money'],
                    'stock'         => $data['number'],
                    'createtime'    => time()
                ];

                $redRes = Db::name('red_envelopes')->insert($redEnvelopes);

                if (!$redRes) return ['code' => 0, 'msg' => '添加红包失败'];
            }

            Db::commit();

            return ['code' => 1, 'msg' => '发布成功'];
        } catch (\think\Exception\DbException $e) {
            // 回滚事务
            Db::rollback();

            return $this->error('操作失败');
        }
    }

    public static function systemPage(array $where)
    {

        $model = new self;
        $count = self::where('status', 1)->count();
        $list = $model->where('status', 1)->page((int) $where['page'], (int) $where['limit'])->order('createtime', 'desc')->select();
        //$list = $model->paginate((int) $where['limit'], false, ['page' => (int) $where['page']]);
        // echo $model->getLastSql();exit;

        $list = $list ? $list->toArray() : [];
        return compact("list", "count");
    }
}
